package com.java01.lang.filechannel;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;


public class FileChannelTest {

	public FileChannelTest() {
		File pipeFile = new File("pipe");
		pipeFile.deleteOnExit();
		if (!pipeFile.exists()) {
			try {
				Runtime.getRuntime().exec("mkfifo " + pipeFile.getAbsolutePath()).waitFor();
			} catch (Exception e) {
				e.printStackTrace();
				return;
			}
		}

		FileInputStream fis=null;
		FileChannel fc=null;
		try {
			fis = new FileInputStream(pipeFile);
			fc = fis.getChannel();
			ByteBuffer buf = ByteBuffer.allocate(1024);
			while(fc.read(buf)!=-1){
				buf.flip();
				System.out.println(">>"+bufferToString(buf));
				buf.clear();
			}
		}catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(fc!=null){
				try {
					fc.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(fis!=null){
				try {
					fis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	public String bufferToString(ByteBuffer buffer){
		byte[] bytes = new byte[buffer.limit()-1];
		buffer.get(bytes, buffer.position(), buffer.limit()-1);
		return new String(bytes);
	}
	
	public static void main(String[] args) {
		new FileChannelTest();
	}

}
